package com.cbwl.eoas.cms.web.controller.security;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.web.filter.PathMatchingFilter;
import org.apache.shiro.web.util.WebUtils;

import com.cbwl.eoas.common.framework.session.SecurityUserDTO;
import com.cbwl.eoas.common.framework.session.SessionManager;

public class MyPathMatchingFilter extends PathMatchingFilter {

	private static final Log LOG = LogFactory.getLog(MyPathMatchingFilter.class);

	/**
	 * 
	 * <p>重写shiro的拦截器</p>
	 * 
	 * @see org.apache.shiro.web.filter.PathMatchingFilter#onPreHandle(javax.servlet.ServletRequest, javax.servlet.ServletResponse, java.lang.Object)
	 * @author: 虞云波 - yuyunbo@3856.cc
	 * @date: Created on 2017年9月29日 下午4:35:18
	 */
	@Override
	protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue)
			throws Exception {
		HttpServletRequest req = WebUtils.toHttp(request);
		String path = req.getServletPath();
		LOG.info("path:" + path);
		boolean ret = false;
		
		HttpServletResponse resp = (HttpServletResponse) response;
		String requestType = req.getHeader("X-Requested-With");

		SecurityUserDTO currUser = SessionManager.getCurrentUser();
		Set<String> auths = currUser.getMenus();
		auths.addAll(getAvoidInterceptionUrl());
		for (String menu : auths) {
			if (ret) {
				break;
			}
			if (menu == null || menu.equals("")) {
				continue;
			}
			ret = pathsMatch(menu, path);
		}

		if (!ret) {
				if (request.getParameter("flag") != null && !request.getParameter("flag").equals("")) {
					// 判断是否是ajax请求
					if ("XMLHttpRequest".equals(requestType)) {
						resp.sendError(800, "您尚未登录,请登录后操作!");
					} else {
						WebUtils.saveRequest(req);
						WebUtils.issueRedirect(req, resp, "/login/loginInit.html");
					}
				} else {
					// 判断是否是ajax请求
					if ("XMLHttpRequest".equals(requestType)) {
						resp.sendError(800, "您尚未登录或登录时间过长,请重新登录!");
					} else {
						// 将请求的URl设置到session中 只有form 请求才提交
						StringBuffer pathSb = new StringBuffer();
						Enumeration enu = request.getParameterNames();
						int flag = 0;
						while (enu.hasMoreElements()) {
							String paraName = (String) enu.nextElement();
							if (flag == 0) {
								pathSb.append("?"+paraName + "=" + request.getParameter(paraName));
							} else {
								pathSb.append("&" + paraName + "=" + request.getParameter(paraName));
							}
							flag++;
						}
						SessionManager.setAttribute(SessionManager.GOTO_URL, path+pathSb.toString());
						WebUtils.saveRequest(req);
						WebUtils.issueRedirect(req, resp, "/main/login");
					}
				}
		}
		return ret;
	}

	public List<String> getAvoidInterceptionUrl() {
		List<String> list = new ArrayList<String>();
		// 免拦截
		list.add("/sysRoleResource/**");
		list.add("/sysuserrole/**");
		return list;
	}
}